package com.ruoyi.common.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class OrderIdGeneratorService {

    private static final String DATE_KEY = "order:date";
    private static final int MAX_SEQUENCE = 9999;

    @Autowired
    private StringRedisTemplate redisTemplate;

    public String generateOrderId(String machineId,String receiveSource) {
        ValueOperations<String, String> ops = redisTemplate.opsForValue();

        String currentDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String lastDate = ops.get(DATE_KEY);

        int sequence;
        if (receiveSource.equals("KF")){
            String SEQUENCE_KEY = "order:KFsequence";
            if (currentDate.equals(lastDate)) {
                // 日期未改变，递增序列号
                sequence = (int) (ops.increment(SEQUENCE_KEY, 1) % (MAX_SEQUENCE + 1));
                if (sequence == 0) { // 如果序列号超过最大值，重置为1（因为0被用作溢出标志）
                    sequence = (int) (ops.increment(SEQUENCE_KEY, 1) % (MAX_SEQUENCE + 1));
                }
            } else {
                // 日期改变，重置日期和序列号
                sequence = 1;
                ops.set(DATE_KEY, currentDate);
                ops.set(SEQUENCE_KEY, Integer.toString(sequence));
            }
        }else {
            String SEQUENCE_KEY = "order:WZsequence";
            if (currentDate.equals(lastDate)) {
                // 日期未改变，递增序列号
                sequence = (int) (ops.increment(SEQUENCE_KEY, 1) % (MAX_SEQUENCE + 1));
                if (sequence == 0) { // 如果序列号超过最大值，重置为1（因为0被用作溢出标志）
                    sequence = (int) (ops.increment(SEQUENCE_KEY, 1) % (MAX_SEQUENCE + 1));
                }
            } else {
                // 日期改变，重置日期和序列号
                sequence = 1;
                ops.set(DATE_KEY, currentDate);
                ops.set(SEQUENCE_KEY, Integer.toString(sequence));
            }
        }


        return String.format("%s-%s-%04d", machineId, currentDate,  sequence);
    }
}
